package com.webdemo02.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.webdemo02.actionform.UserForm;
import com.webdemo02.util.DBHandler;

public class UpdateUser extends DispatchAction {

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UserForm user = (UserForm) form;
		int id = user.getId();
		String name = user.getName();
		String sql = "update xml01_user set name=? where id=?";
		Connection conn = DBHandler.newInstance().getConnection();
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, name);
		pstmt.setInt(2, id);
		pstmt.executeUpdate();
		ActionForward actionForward = new ActionForward("/QueryUser.do");
		actionForward.setRedirect(true);
		return actionForward;
	}

	public ActionForward show(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		UserForm user = (UserForm)form;
		int id = user.getId();
		String sql = "select id,name from xml01_user where id=?";
		Connection conn = DBHandler.newInstance().getConnection();
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, id);
		ResultSet rs = pstmt.executeQuery();
		if (rs.next()) {
			user = new UserForm();
			int iD = rs.getInt("id");
			String name = rs.getString("name");
			user.setId(iD);
			user.setName(name);
		}
		request.setAttribute("user", user);
		return mapping.findForward("update");
	}

}
